package com.woniuxy.service.auth.impl;

import com.woniuxy.entity.Permission;
import com.woniuxy.entity.Role;
import com.woniuxy.entity.Emp;
import com.woniuxy.entity.EmpExample;
import com.woniuxy.mapper.custom.CustomRoleMapper;
import com.woniuxy.mapper.custom.CustomEmpMapper;
import com.woniuxy.service.auth.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 马踏东京赏樱花
 */
@Service
@Transactional
public class AuthServiceImpl implements AuthService {
    @Autowired
    private CustomEmpMapper empMapper;

    @Autowired
    private CustomRoleMapper roleMapper;

    @Override
    public Emp login(String uacc, String upwd) {
        EmpExample ue = new EmpExample();
        ue.or().andEmpUaccEqualTo(uacc).andEmpUpwdEqualTo(upwd);
        List<Emp> list = empMapper.selectByExample(ue);

        if (list.size() > 0) {
            Emp emp = list.get(0);

            List<Integer> roleIds = empMapper.findRoleIdsByEmpId(emp.getEmpId());

            List<Role> roles = roleIds.stream()
                    .map(roleId -> roleMapper.findRoleWithPermissionsByRoleId(roleId))
                    .collect(Collectors.toList());

            Set<Permission> permissions = new HashSet<>();
            roles.forEach(role -> {
                permissions.addAll(role.getPermissions());
            });

            emp.setPermissions(new ArrayList(permissions));

            return emp;
        }
        throw new RuntimeException("认证失败");
    }

    @Override
    public String updateUpwd(String oldUpwd, String newUpwd, Integer empId) {

        List<Emp> list = empMapper.selectByExample(null);
        if (list.size() > 0) {
            Emp emp = list.get(0);
            emp.setEmpUpwd(newUpwd);
            int rows = empMapper.updatePassword(empId,newUpwd);
        }
        return newUpwd;
    }
//    @Override
//    public Emp register(Emp emp) {
//        int i = empMapper.insertSelective(emp);
//        if (i == 1) {
//            return emp;
//        }
//        throw new RuntimeException("注册失败");
//    }

}
